<?php
/**
 * Created by PhpStorm.
 * User: ront
 * Date: 2018/8/7
 * Time: 16:47
 */

namespace App\Services;

use App\Models\Admin\Permission;
use App\Models\Admin\Role;

class Admin
{
    protected $permissions;

    /**
     * 查询用户权限
     * @param int $role_id
     * @return null|mixed
     */
    public static function getPermission($role_id = 0)
    {
        $role = Role::find($role_id);

        if (!$role) {
            return null;
        }

        $res = ['role' => $role->name];

        if ($role->permissions === '*') {
            $res['permissions'] = '*';
            return $res;
        }



        $permissions = Permission::whereIn('id', explode(',', $role->permissions))->get(['name', 'name_zh']);

        $res['permissions'] = static::parsePermissions($permissions);

        return $res;
    }

    /**
     * 格式化权限
     * @param $permissions
     * @return array
     */
    public static function parsePermissions($permissions)
    {
        $res = [];

        foreach ($permissions as $permission) {
            if ($permission instanceof Permission) {
                $permission = $permission->toArray();
            }
            $res[$permission['name']] = $permission['name_zh'];
        }

        return $res;
    }

    /**
     * 格式化id
     * @param $roles
     * @return null|string
     */

}